﻿using System;
using System.Collections.Generic;
using System.Linq;
using Framework.Exceptions.RepositoryExceptions;
using Interfaces.Enums;
using Interfaces.Repositories;
using Interfaces.RepositoryModels.InternalModels.UserRoleModels;

namespace SQLRepositories.UserRoleRepositories
{
    public class RoleRepository : EntityBaseRepository<RoleModel>, IRoleRepository
    {
        public RoleRepository(IDBEconomicInformationServiceContext context):base(context)
        {}

        public void Create(RoleModel item)
        {
            if(item == null)
                throw new ArgumentNullException("item");

            Insert(() =>
                {
                    Context.Roles.Add(item);
                    Context.SaveChanges();
                });
        }

        public RoleModel GetById(Guid id)
        {
            return Get(()=>Context.Roles.FirstOrDefault(x => x.Id.Equals(id)));
        }

        public void Delete(Guid id)
        {
            base.Delete(() =>
                {
                     var role = Context.Roles.FirstOrDefault(x => x.Id.Equals(id));

                     if (role == null)
                          throw new EntityNotFoundException("Role");

                     Context.Roles.Remove(role);
                     Context.SaveChanges();
                });
        }

        public void Delete(RoleModel item)
        {
            base.Delete(() =>
            {
                Context.Roles.Remove(item);
                Context.SaveChanges();
            });
        }

        public RoleModel GetByType(RoleType type)
        {
            return Get(()=>Context.Roles.FirstOrDefault(x => x.Type == type));
        }

        public IEnumerable<RoleModel> GetAll()
        {
            return Get(()=>Context.Roles.ToList());
        }
    }
}
